package com.cxy.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.cxy.dao.IBaseDao;

public class BaseDaoImpl<T> extends HibernateDaoSupport implements IBaseDao<T> {

	@Resource(name = "sessionFactory")
	public void setSuperSessionFactory(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

	/**
	 * 创建一个Class的对象来获取泛型的class
	 */
	private Class<T> clz;

	@SuppressWarnings("unchecked")
	public Class<T> getClz() {
		if (clz == null) {
			clz = (Class<T>) (((ParameterizedType) this.getClass()
					.getGenericSuperclass()).getActualTypeArguments()[0]);
		}
		return clz;
	}

	@Override
	public void add(T t) {
		//this.getHibernateTemplate().save(t);
		this.getHibernateTemplate().merge(t); 	// 解决多线程并发操作
	}

	@Override
	public void saveOrUpdate(T t) {
			this.getHibernateTemplate().saveOrUpdate(t);
	}

	@Override
	public void delete(int id) {
		this.getHibernateTemplate().delete(this.load(id));
	}

	@Override
	public void update(T t) {
		this.getHibernateTemplate().update(t);
	}

	@Override
	public T load(int id) {
		return this.getHibernateTemplate().load(getClz(), id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> list(String hql, Object... args) {
		Query query = this.getSession().createQuery(hql);
		for (int i = 0; i < args.length; i++) {
			query.setParameter(i, args[i]);
		}
		List<T> list = query.list();
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <X> List<X> find(int start, int limit, String hql, Object... values) {
		if (limit == 0) {
			limit = 1;
		}

		Query query = createQuery(hql, values);
		query.setFirstResult(start);
		query.setMaxResults(limit);
		return query.list();

	}

	public Query createQuery(final String queryString, final Object... values) {
		Query query = this.getSession().createQuery(queryString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}

		return query;
	}

}